//
//  JCReportCommentsVC.m
//  SquashSpark
//
//  Created by 郭吉成 on 2017/11/30.
//  Copyright © 2017年 Coollang-YF. All rights reserved.
//

#import "JCReportCommentsVC.h"
#import "JCReportCommentsCell.h"
#import "JCClubApi.h"
#import "JCReportCommentModel.h"

#define     kInputViewMinHeight     28

@interface JCReportCommentsVC ()<UITableViewDataSource, UITableViewDelegate, UITextViewDelegate>
@property (weak, nonatomic) IBOutlet UIView *noReportView;
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
        
@property (weak, nonatomic) IBOutlet UITextView *coachReviewInput;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *coachReviewHeight;
@property (weak, nonatomic) IBOutlet UILabel *coachReviewLabel;
@property (weak, nonatomic) IBOutlet UITextView *trainingSuggestionInput;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *trainingSuggestionHeight;
@property (weak, nonatomic) IBOutlet UILabel *trainingSuggestionLabel;
@property (weak, nonatomic) IBOutlet UITextView *learningCourseInput;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *learningCourseHeight;
@property (weak, nonatomic) IBOutlet UILabel *learningCourseLabel;

@property (weak, nonatomic) IBOutlet UIButton *submitBtn;

@property (strong, nonatomic) UITextView *currentTextView;
@property (assign, nonatomic) CGFloat offsetY;
@property (assign, nonatomic) CGFloat keyBoardHeight;
@property (assign, nonatomic) CGFloat lastOffsetY;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *showViewContentHeight;

@end

@implementation JCReportCommentsVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initCode];
}

- (void)initCode{
    __weak typeof(self)weakSelf = self;
    _scrollView.alwaysBounceVertical = YES;
    _noReportView.hidden = YES;
    if (_userType == ClubUserTypeGeneral){
        _tableView.hidden = NO;
        _scrollView.hidden = YES;
        [JCClubApi getReportCommentForClubID:_clubID userID:_userID year:_year yearWeek:_yearWeek complete:^(NSError *error, JCReportCommentModel *commentModel) {
            if (error) {
                [weakSelf.hud showErrorWithString:error.domain dimissAfterSecond:2];
            }else{
                [weakSelf.hud dismiss];
                weakSelf.commentModel = commentModel;
                [weakSelf.tableView reloadData];
                if (commentModel == nil) {
                    weakSelf.noReportView.hidden = NO;
                    weakSelf.tableView.hidden = YES;
                }
            }
        }];
    }else if (_userType == ClubUserTypeAdmin){
        _scrollView.hidden = NO;
        _tableView.hidden = YES;
    }
//    _coachReviewInput.attributedPlaceholder = [self creatAttributedString:@"CoachReview" font:kOpenSansFont(OpenSansBold, 16) color:[UIColor whiteColor]];
//    _trainingSuggestionInput.placeholderAttributedText = [self creatAttributedString:@"TrainingSuggestion" font:kOpenSansFont(OpenSansBold, 16) color:[UIColor whiteColor]];
//    _learningCourseInput.placeholderAttributedText = [self creatAttributedString:@"LearningCourse" font:kOpenSansFont(OpenSansBold, 16) color:[UIColor whiteColor]];
    _submitBtn.layer.cornerRadius = 3;
    _submitBtn.layer.masksToBounds = YES;
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
}

- (void)keyboardWillShow:(NSNotification *)notification{
    NSDictionary *userInfo = [notification userInfo];
    NSValue *value = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [value CGRectValue];
    _keyBoardHeight = keyboardRect.size.height - 40;
//    CGFloat time = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    
    CGFloat valueY = 0;
    if (_currentTextView == _coachReviewInput) {
        if ([_currentTextView.text isEqualToString:@"Coach Review"]) {
            _currentTextView.text = @"";
        }
        valueY = _coachReviewLabel.frame.origin.y;
    }else if (_currentTextView == _trainingSuggestionInput){
        if ([_currentTextView.text isEqualToString:@"Training Suggestion"]) {
            _currentTextView.text = @"";
        }
        valueY = _trainingSuggestionLabel.frame.origin.y;
    }else if (_currentTextView == _learningCourseInput){
        if ([_currentTextView.text isEqualToString:@"Learning Course"]) {
            _currentTextView.text = @"";
        }
        valueY = _learningCourseLabel.frame.origin.y;
    }
    _offsetY = valueY - _keyBoardHeight;
    _lastOffsetY = _scrollView.contentOffset.y;
    [_scrollView setContentOffset:CGPointMake(0, _offsetY) animated:YES];
//    [UIView animateWithDuration:time animations:^{
//        [self.view layoutIfNeeded];
//    }];
}

- (void)keyboardWillHide:(NSNotification *)notification{
//    NSDictionary *userInfo = [notification userInfo];
//    NSValue *value = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
//    CGRect keyboardRect = [value CGRectValue];
    //    int height = keyboardRect.size.height;
//    CGFloat time = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
//    [UIView animateWithDuration:time animations:^{
//        [self.view layoutIfNeeded];
//    }];
    if (_currentTextView == _coachReviewInput) {
        if ([_currentTextView.text isEqualToString:@""]) {
            _currentTextView.text = @"Coach Review";
        }
    }else if (_currentTextView == _trainingSuggestionInput){
        if ([_currentTextView.text isEqualToString:@""]) {
            _currentTextView.text = @"Training Suggestion";
        }
    }else if (_currentTextView == _learningCourseInput){
        if ([_currentTextView.text isEqualToString:@""]) {
            _currentTextView.text = @"Learning Course";
        }
    }
    [_scrollView setContentOffset:CGPointMake(0, _lastOffsetY) animated:YES];
}

#pragma mark -- UITextView代理
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView{
    _currentTextView = textView;
    return YES;
}
- (BOOL)textViewShouldEndEditing:(UITextView *)textView{
    return YES;
}
- (void)textViewDidChange:(UITextView *)textView{
   
    if (textView == _coachReviewInput) {
        _coachReviewLabel.text = [NSString stringWithFormat:@"%ld/300",_coachReviewInput.text.length];
    }else if (textView == _trainingSuggestionInput){
        _trainingSuggestionLabel.text = [NSString stringWithFormat:@"%ld/300",_trainingSuggestionInput.text.length];
    }else if (textView == _learningCourseInput){
        _learningCourseLabel.text = [NSString stringWithFormat:@"%ld/300",_learningCourseInput.text.length];
    }
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if ([text isEqualToString:@"\n"]) {
        [self.view endEditing:YES];
        return NO;
    }
    UITextView *vv = [[UITextView alloc] initWithFrame:CGRectMake(0, 0, kYFScreenWidth - 30, 0)];
    vv.textColor = [UIColor whiteColor];
    vv.font = kOpenSansFont(OpenSansRegular, 16);
    vv.text = [textView.text stringByAppendingString:text];
    [vv sizeToFit];
    CGFloat height = vv.bounds.size.height;
    
    if (textView == _coachReviewInput) {
        _coachReviewHeight.constant = MAX(height, kInputViewMinHeight);
    }else if (textView == _trainingSuggestionInput){
        _trainingSuggestionHeight.constant = MAX(height, kInputViewMinHeight);
    }else if (textView == _learningCourseInput){
        _learningCourseHeight.constant = MAX(height, kInputViewMinHeight);
    }
    _showViewContentHeight.constant = 466+(_coachReviewHeight.constant + _trainingSuggestionHeight.constant + _learningCourseHeight.constant);
    [UIView animateWithDuration:.3 animations:^{
        [self.view layoutIfNeeded];
        CGFloat valueY = 0;
        if (textView == _coachReviewInput) {
            valueY = _coachReviewLabel.frame.origin.y;
        }else if (textView == _trainingSuggestionInput){
            valueY = _trainingSuggestionLabel.frame.origin.y;
        }else if (textView == _learningCourseInput){
            valueY = _learningCourseLabel.frame.origin.y;
        }
        _offsetY = valueY - _keyBoardHeight;
        [_scrollView setContentOffset:CGPointMake(0, _offsetY) animated:NO];
    } completion:^(BOOL finished) {
        
    }];
    return YES;
}

- (IBAction)submitAction:(UIButton *)sender {
    sender.enabled = NO;
    __weak typeof(self)weakSelf = self;
    if (![_coachReviewInput.text isEqualToString:@"Coach Review"] &&
        ![_trainingSuggestionInput.text isEqualToString:@"Training Suggestion"] &&
        ![_learningCourseInput.text isEqualToString:@"Learning Course"] ) {
        [self.hud showWithMaskType:WSProgressHUDMaskTypeClear];
        [JCClubApi commentReportForClubID:_clubID userID:_userID year:_year yearWeek:_yearWeek coachReview:_coachReviewInput.text suggestion:_trainingSuggestionInput.text course:_learningCourseInput.text complete:^(NSError *error) {
            if (error) {
                [weakSelf.hud showErrorWithString:error.domain dimissAfterSecond:2];
            }else{
                [weakSelf.hud showSuccessWithStatus:@"Success!" dimissAfterSecond:2];
            }
        }];
    }else{
        [self.hud showErrorWithString:NSLocalizedString(@"Please complete the information",@"请将信息填写完整") dimissAfterSecond:2];
        weakSelf.submitBtn.enabled = YES;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _userType==ClubUserTypeAdmin?0:(_commentModel?3:0);
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    JCReportCommentsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"JCReportCommentsCoachReviewCell" forIndexPath:indexPath];
//    cell.delegate = self;
    if (_userType == ClubUserTypeAdmin) {
        
    }else if (_userType == ClubUserTypeGeneral){
        [cell setValueForIndexPath:indexPath commemtModel:_commentModel];
    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 100;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
